import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

class Record(db.Model):
  author = db.UserProperty()
  question = db.StringProperty(multiline=True)
  answer = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)
  tags = db.ListProperty(basestring)
  rate = db.IntegerProperty(choices=[0, 1, 2, 3, 4, 5])

class Tags(db.Model):
  tags = db.StringProperty(required=True)


class MainPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if user:
      login_or_out_url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      login_or_out_url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    if user:
      records_query = Record.all().filter('author = ', user).order('-date')
    else:
      records_query = Record.all().order('-date')
    records = records_query.fetch(10)

    template_values = {
      'user': user,
      'records': records,
      'login_or_out_url': login_or_out_url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'home.html')
    self.response.out.write(template.render(path, template_values))



  def post(self):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.uri))

    new_record = Record(rate=0)
    new_record.author = user
    new_record.question = self.request.get('question')
    new_record.answer = self.request.get('answer')
    new_record.tags = self.request.get('tags').split()
    if new_record.question and new_record.answer:
      new_record.put()
    self.redirect('/')

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/new_post', MainPage)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
